/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package processamento;

import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import javax.media.jai.PlanarImage;
import javax.media.jai.TiledImage;

/**
 *
 * @author Igor
 */
public class OperadorSegmentaPele {

    public static PlanarImage segmentaPele(PlanarImage pi) {
        int width = pi.getWidth();
        int height = pi.getHeight();

        Raster inputRaster = pi.getData();
        WritableRaster outputRaster = inputRaster.createCompatibleWritableRaster();
            int[] pixel = new int[3];

            for(int i =0; i < width; i++)
            {
                for (int h =0;h<height;h++) {
                    pixel = inputRaster.getPixel(i, h, pixel);
                    if (checaPixel(calculaWr(pixel),calculaLuminancia(pixel),calculaHue(pixel),pixel[1])) {
                        pixel[0]=255;pixel[1]=255;pixel[2]=255;
                    } else {
                        pixel[0]=0;pixel[1]=0;pixel[2]=0;
                    }
                    outputRaster.setPixel(i, h,pixel);
                }
            }

            TiledImage ti = new TiledImage(pi, width, height);
            ti.setData(outputRaster);
            return ti;
    }

    public static double calculaHue(int[] pixel) {
       double hue = Math.atan2(2*pixel[0]-pixel[1]-pixel[2], Math.sqrt(3)*(pixel[1]-pixel[2]));
       return hue;
    }

    public static double calculaLuminancia(int[] pixel) {
        double Y = (double)0.299*(double)pixel[0] + (double)0.587*(double)pixel[1] + (double)0.114*(double)pixel[2];
        return Y;
    }

    public static double calculaWr(int[] pixel) {
        if (pixel[0]+pixel[1]+pixel[2]!=0) {
            double termoA = (pixel[0]/(pixel[0]+pixel[1]+pixel[2]))-(1/3);
            double termoB = (2/(pixel[0]+pixel[1]+pixel[2]))-(1/3);

            double Wr = Math.pow(termoA, 2)+Math.pow(termoB, 2);
            return Wr;
        } else {
            return 0;
        }
    }

    private static boolean checaPixel(double Wr, double Y, double Hue, int G) {
        if (Hue>-17.4545 && Hue<26.666) {
            if (G-Y<-5.9216) {
                if (Wr<0.0271) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}
